package com.asimplefox.service.stand;

import com.asimplefox.serurity.TokenManager;
import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.entity.Role;
import com.asimplefox.entity.User;
import com.asimplefox.entity.vo.UserVo;
import com.asimplefox.service.IRoleService;
import com.asimplefox.service.IUserService;
import com.asimplefox.service.abst.ResultU;
import io.github.kloping.judge.Judge;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author github.kloping
 */
@Component
public class LoginDetailService implements ResultU {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    TokenManager tokenManager;

    public Object logoutNow(UserDetails userDetails, HttpServletRequest request, HttpServletResponse response) {
        return tokenManager.remove(userDetails.getUsername()) ? success("登出成功") : define("登出失败");
    }

    public String loginNow(UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        if (Judge.isEmpty(userVo.getPwd())) {
            response.setStatus(400);
            return result(400, "密码不能为空");
        }
        return loginNowR(userVo, request, response);
    }

    private String loginNowR(UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        UsernamePasswordAuthenticationToken usernamePassword =
                new UsernamePasswordAuthenticationToken(userVo.getUsername(), userVo.getPwd());
        try {
            Authentication authenticate = authenticationManager.authenticate(usernamePassword);
            Object principal = authenticate.getPrincipal();
            UserRoleDetails details = (UserRoleDetails) principal;
            details.setPassword("");
            details.getUser().setPwd("");
            String token = UUID.randomUUID().toString();
            HttpSession httpSession = request.getSession(true);
            httpSession.setAttribute("token", token);
            httpSession.setMaxInactiveInterval(60 * 60 * 24 * 7);
            tokenManager.set(token, details);
            return result(200, "登录成功", "token", token);
        } catch (AuthenticationException e) {
            response.setStatus(400);
            return result(400, "登录失败:" + e.getMessage());
        }
    }

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    public Object loginNowWithGoogle(AuthResponse info, HttpServletRequest request, HttpServletResponse response) {
        if (info.getData() == null) {
            response.setStatus(400);
            return result(400, "登录异常,请重新进入刷新网页");
        }
        AuthUser authUser = (AuthUser) info.getData();
        User user = userService.lambdaQuery().eq(User::getUsername, authUser.getUsername()).one();
        if (user == null) user = userService.lambdaQuery().eq(User::getEmail, authUser.getEmail()).one();
        if (user == null) {
            user = new User()
                    .setNickname(authUser.getNickname())
                    .setAvatar(authUser.getAvatar())
                    .setEmail(authUser.getEmail())
                    .setTelephone("")
                    .setPwd("")
                    .setReg("google")
                    .setUsername(authUser.getUsername());
            if (userService.save(user)) {
                roleService.save(new Role().setUserId(user.getId()).setUserRole("user"));
            } else {
                response.setStatus(400);
                return result(400, "登录异常");
            }
        }
        return loginNowR(new UserVo(user.getUsername(), user.getPwd()), request, response);
    }
}
